package jp.co.sharp.android.parents.kidsguard.activity.setting;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.GpsSettingActivity;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestCodeConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;
import jp.co.sharp.android.parents.kidsguard.utils.CommonUtils;

public class QuickDispatchSettingActivity extends AppCompatActivity {
    private App mApp;
    private ParentBleTransfer mParentBleTransfer;
    //    private App mApp;
    private KidInfoEntity mKidInfoEntity;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private boolean mEditFlag = false;
    private boolean mLockFlag = false;
    // 0: lock, 0: init , 1: getInfo , 2: setInfo, 3 :end
    private int mViewProcess = 0;
    private JSONArray pageData;
    private int mPositionKey;
    private Button mSubmitBtn;
    private boolean SCREEN_OPERATE = false;
    private int mPageCode = PageSerialNumConstants.PAGE_SERIAL_NUM_QUICK;

    private Map<Integer, Integer> mContactIdMap = new HashMap<>();
    private boolean mUnReceiver = true;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    private static final String TAG = "TAG";
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mApp = (App) getApplication();
        super.onCreate(savedInstanceState);
        Log.i(TAG, "QuickDispatchSettingActivity_onCreate");
        setContentView(R.layout.activity_quick_dispatch_setting);
        initReceiver();
        initActivity();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "QuickDispatchSettingActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    toopenDig();
                }
                mSystemHomeFlag = false;
            }
        }
    }

    @Override
    protected void onStop() {
        Log.i(TAG, "QuickDispatchSettingActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "QuickDispatchSettingActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        initReceiver();
        if (requestCode == 100 && resultCode == RequestCodeConstants.CONTACT_OPT) {
            ContactListDto dto = (ContactListDto) data.getSerializableExtra(Constants.KEY_CONTACT_OPT);
            JSONObject json = new JSONObject();
            try {
                for (int i = 0; i < pageData.length(); i++) {
                    if (pageData.getJSONObject(i).getInt("key") == mPositionKey) {
                        pageData.remove(i);
                        break;
                    }
                }
                json.put("id", dto.getId());
                json.put("key", mPositionKey);
                json.put("name", dto.getName());
                json.put("phone", dto.getPhone());
                json.put("portrait", dto.getPortrait());
                pageData.put(json);
                alterBtn();
                LoadingPage(null);
            } catch (JSONException e) {
                Log.e(TAG, e.getMessage());
            }
        }

    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }

    private void initActivity() {
        Log.i(TAG, "QuickDispatchSettingActivity_initActivity");
        TextView textView = (TextView) findViewById(R.id.settingSecondMenu);
        String strSecondMenu = mKidInfoEntity.getKidName() + "のキッズケータイ";
        textView.setText(strSecondMenu);
        mSubmitBtn = findViewById(R.id.submitBtn);
        mSubmitBtn.setOnClickListener((view) -> {
            // Dlg
            String message = "キッズケータイへ反映中..";
            mDealWithWaitingDlg = new DealWithWaitingDlg(QuickDispatchSettingActivity.this, R.style.commonDlg, message, true);
            mDealWithWaitingDlg.show();
            new BusinessThread(sendSetToKid(), mParentBleTransfer, mKidInfoEntity).start();
        });
        // Dlg
        String message = "キッズケータイから情報を取得しています...";
        mDealWithWaitingDlg = new DealWithWaitingDlg(QuickDispatchSettingActivity.this, R.style.commonDlg, message, true);
        mDealWithWaitingDlg.show();
        new BusinessThread(Constants.SEND_KID_IS_USING, mParentBleTransfer, mKidInfoEntity).start();
    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        mKidInfoEntity = mApp.findKidInfoBySelect();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // Bluetooth
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = mApp.getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        SCREEN_OPERATE = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                           toopenDig();
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        SCREEN_OPERATE = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(QuickDispatchSettingActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        ((App) getApplication()).updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(QuickDispatchSettingActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(() -> {
                            processWarringDlg.dismiss();
                            // ページジャンプ
                            mPageJumpFlag = true;
                            Intent intent1 = new Intent();
                            intent1.setClass(QuickDispatchSettingActivity.this, SettingActivity.class);
                            startActivity(intent1);
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };
    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    switch (mViewProcess) {
                        case Constants.SEND_KID_ENTER:
                            if (!mEditFlag) {
                                mViewProcess = Constants.SEND_KID_GET_INFO;
                                new BusinessThread(getKidDataRequestJson(), mParentBleTransfer, mKidInfoEntity).start();
                            } else {
                                mEditReopening = false;
                                mDealWithWaitingDlg.dismiss();
                            }

                            break;
                        case Constants.SEND_KID_EXIT:
                            if (mDealWithWaitingDlg != null && mDealWithWaitingDlg.isShowing()) {
                                mDealWithWaitingDlg.dismiss();
                            }
                            if (!SCREEN_OPERATE) {
                                QuickDispatchSettingActivity.this.finish();
                            }
                            break;
                    }
                }
            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                String retStr = bluetoothReceiverDto.getRetStr();
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(retStr);
                    if (mLockFlag && RequestMethodConstants.METHOD_GET_QUICK_CALLS.equals(jsonObject.getString("method"))) {
                        mEditFlag = true;
                        mDealWithWaitingDlg.dismiss();
                        LoadingPage(jsonObject.getJSONArray("data"));
                    } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getString("result").equals(Constants.ON_SYNC_RESULT)) {
                            backActivity(null);
                        } else {
                            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                                mDealWithWaitingDlg.dismiss();
                            }
                            String message = "キッズケータイへ反映できませんでした";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(QuickDispatchSettingActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                }
                            });
                        }
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(QuickDispatchSettingActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(() -> {
                            processWarringDlg.dismiss();
                            backActivity(null);
                        });
                    } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getJSONObject("data").getString("state").equals(Constants.IS_USING_OK)) {
                            mLockFlag = true;
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, 5, mParentBleTransfer, mKidInfoEntity).start();
                        } else {
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(QuickDispatchSettingActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(() -> {
                                processWarringDlg.dismiss();
                                backActivity(null);
                            });
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }

            }
        }
    };

    public void backActivity(View view) {
        if (isPageChange() && view != null) {
            String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
            DelDeviceConfirmDlg mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(QuickDispatchSettingActivity.this, R.style.commonDlg, message);
            mDelDeviceConfirmDlg.show();
            mDelDeviceConfirmDlg.setOnOperateSetListener(() -> {
                mDelDeviceConfirmDlg.dismiss();
                mViewProcess = Constants.SEND_KID_EXIT;
                new BusinessThread(Constants.SEND_KID_EXIT, 5, mParentBleTransfer, mKidInfoEntity).start();
            });
        } else {
            mViewProcess = Constants.SEND_KID_EXIT;
            new BusinessThread(Constants.SEND_KID_EXIT, 5, mParentBleTransfer, mKidInfoEntity).start();
        }
    }

    private void LoadingPage(JSONArray dataList) throws JSONException {
        if (mDealWithWaitingDlg != null && mDealWithWaitingDlg.isShowing()) {
            mDealWithWaitingDlg.dismiss();
        }
        TableRow tableRow = findViewById(R.id.tableRow);
        tableRow.removeAllViews();
        if (dataList != null) {
            pageData = dataList;
        }
        for (int i = 0; i < 3; i++) {
            boolean existFlag = false;
            JSONObject data = null;
            for (int x = 0; x < pageData.length(); x++) {
                data = pageData.getJSONObject(x);
                int key = data.getInt("key");

                if (key == i) {
                    if (data.getInt("id") == -1) {
                        setPageContactName(i, "連絡先から選択");
                        break;
                    }
                    existFlag = true;
                    setPageContactName(i, data.getString("name") + "\n" + data.getString("phone"));
                    break;
                }
            }
            if (existFlag) {
                tableRow.addView(getPortraitView(data.getInt("portrait"), i));
            } else {
                tableRow.addView(getAddButView(i));
            }
            if (dataList != null) {
                if (existFlag)
                    mContactIdMap.put(i, data.getInt("id"));
                else
                    mContactIdMap.put(i, -1);
            }

        }
    }

    private View getPortraitView(int pPortrait, int key) {
        RelativeLayout relativeLayout = new RelativeLayout(QuickDispatchSettingActivity.this);
        TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(getPixelsFromDp(88), getPixelsFromDp(88));
        layoutParams.setMargins(getPixelsFromDp(25), 0, 0, 0);
        relativeLayout.setLayoutParams(layoutParams);

        ImageView portrait = new ImageView(QuickDispatchSettingActivity.this);
        portrait.setImageResource(CommonUtils.chooseImage(pPortrait));
        portrait.setBackgroundColor(QuickDispatchSettingActivity.this.getResources().getColor(R.color.colorCloseBackgroundBtn));
        portrait.setScaleType(ImageView.ScaleType.FIT_CENTER);
        TableRow.LayoutParams layoutParams2 = new TableRow.LayoutParams(getPixelsFromDp(88), getPixelsFromDp(88));
        portrait.setLayoutParams(layoutParams2);
        relativeLayout.addView(portrait);

        ImageButton imageButton = new ImageButton(QuickDispatchSettingActivity.this);
        TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(getPixelsFromDp(28), getPixelsFromDp(28));
        buttonParams.setMargins(getPixelsFromDp(65), 0, 0, 0);
        imageButton.setLayoutParams(buttonParams);
        imageButton.setBackgroundColor(QuickDispatchSettingActivity.this.getResources().getColor(R.color.colorCloseBackgroundBtn));
        imageButton.setImageResource(R.mipmap.round_cancel_24px);
        relativeLayout.addView(imageButton);
        imageButton.setOnClickListener((view) -> {
            for (int i = 0; i < pageData.length(); i++) {
                try {
                    JSONObject data = pageData.getJSONObject(i);
                    if (key == data.getInt("key")) {
                        data.put("id", -1);
                        LoadingPage(null);
                    }
                } catch (JSONException e) {
                    Log.e(TAG, e.getMessage());
                }
            }
            alterBtn();
        });
        return relativeLayout;
    }

    private View getAddButView(int key) {
        ImageButton imageButton = new ImageButton(QuickDispatchSettingActivity.this);
        TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(getPixelsFromDp(88), getPixelsFromDp(88));
        buttonParams.setMargins(getPixelsFromDp(25), 0, 0, 0);
        imageButton.setLayoutParams(buttonParams);
        imageButton.setBackgroundColor(QuickDispatchSettingActivity.this.getResources().getColor(R.color.colorCloseBackgroundBtn));
        imageButton.setImageResource(R.drawable.svg_round_add_box);
        imageButton.setOnClickListener((view) -> {
//            mPageJumpFlag = true;
            Intent intent = new Intent(QuickDispatchSettingActivity.this, ContactOptActivity.class);
            startActivityForResult(intent, RequestCodeConstants.CONTACT_OPT);
            mPositionKey = key;
        });

        return imageButton;
    }

    private void setPageContactName(int index, String name) {
        TextView textView;
        switch (index) {
            case 0:
                textView = QuickDispatchSettingActivity.this.findViewById(R.id.contact_name_1);
                break;
            case 1:
                textView = QuickDispatchSettingActivity.this.findViewById(R.id.contact_name_2);
                break;
            case 2:
                textView = QuickDispatchSettingActivity.this.findViewById(R.id.contact_name_3);
                break;
            default:
                textView = QuickDispatchSettingActivity.this.findViewById(R.id.contact_name_3);
                break;
        }
        textView.setText(name);
    }

    private JSONObject getKidDataRequestJson() {
        JSONObject jsonObject = new JSONObject();
        try {
//            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_GET_QUICK_CALLS);
            jsonObject.put("data", JSONObject.NULL);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return jsonObject;
    }

    private void alterBtn() {
        if (isPageChange()) {
            if (!mSubmitBtn.isEnabled()) {
                mSubmitBtn.setEnabled(true);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
            }
        } else {
            if (mSubmitBtn.isEnabled()) {
                mSubmitBtn.setEnabled(false);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
            }
        }
    }

    private Boolean isPageChange() {
        try {
            for (Integer key : mContactIdMap.keySet()) {
                boolean isExist = false;
                for (int i = 0; i < pageData.length(); i++) {
                    JSONObject json = pageData.getJSONObject(i);
                    if (json.getInt("key") == key) {
                        isExist = true;
                        if (json.getInt("id") != mContactIdMap.get(key)) {
                            return true;
                        }
                        break;
                    }
                }
                if (!isExist) {
                    if (mContactIdMap.get(key) != -1) {
                        return true;
                    }
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, e.getMessage());
        }
        return false;
    }

    private JSONObject sendSetToKid() {
        JSONObject sendJson = new JSONObject();
        try {
            sendJson = new JSONObject();
            sendJson.put("method", RequestMethodConstants.METHOD_SET_QUICK_CALLS);
            sendJson.put("data", pageData);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return sendJson;
    }

    private int getPixelsFromDp(int size) {

        DisplayMetrics metrics = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        return (size * metrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;

    }

    private void toopenDig() {
        if (!mEditReopening) {
            String message = "編集を再開しています...";
            mDealWithWaitingDlg = new DealWithWaitingDlg(QuickDispatchSettingActivity.this, R.style.commonDlg, message, false);
            mDealWithWaitingDlg.show();
            SCREEN_OPERATE = true;
            mViewProcess = Constants.SEND_KID_IS_USING;
            new BusinessThread(Constants.SEND_KID_IS_USING,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    null,
                    PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
            // ブロードキャストの再登録
            unregisterReceiver(systemReceiver);
            initReceiver();
            mEditReopening = true;
        }
    }
}
